package com.tingyu.blog.service;

import com.tingyu.blog.MyNotFoundException;
import com.tingyu.blog.dao.BlogRepository;
import com.tingyu.blog.po.Blog;
import com.tingyu.blog.po.Type;
import com.tingyu.blog.util.MarkdownUtils;
import com.tingyu.blog.util.MyBeanUtils;
import com.tingyu.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{
    //注入blogRepository仓库
    @Autowired
    private BlogRepository blogRepository;

    /**
     * 获取一个博客
     * @param id
     * @return 返回blog对象
     */
    @Override
    public Blog getBlog(int id) {
        return blogRepository.getOne(id);
    }

    /**
     * 数据库取出的纯文本转为HTML格式文本
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Blog getAndConvert(int id) {
        Blog blog = blogRepository.getOne(id);
        if (blog == null){
            throw new MyNotFoundException("博客不存在！");
        }
        Blog b =new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        String convertedContent = MarkdownUtils.markdownToHtmlExtensions(content);
        b.setContent(convertedContent);
        //浏览次数累加
        blogRepository.updateViews(id);

        return b;
    }


    /**
     * 多条件组合查询博客列表
     * @param pageable
     * @param blog
     * @return
     */
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId() != null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    /**
     * 根据标签id查询博客
     * @param tagId
     * @param pageable
     * @return
     */
    @Override
    public Page<Blog> listBlog(int tagId, Pageable pageable) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join = root.join("tags");
                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    /**
     * 按年份查询博客
     * @return
     */
    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogRepository.findGroupYear();
        Map<String,List<Blog>> map = new HashMap<>();
        for (String year : years) {
            map.put(year,blogRepository.findByYear(year));
        }
        return map;
    }

    /**
     * 获取博客总数
     * @return
     */
    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    /**
     * 获取所有博客
     * @param pageable
     * @return 返回博客分页对象
     */
    @Override
    public Page<Blog> getBlogs(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }


    /**
     * 最新推荐博客列表
     * @param size 条数
     * @return
     */
    @Override
    public List<Blog> listRecommendBlogTop(int size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable = PageRequest.of(0,size,sort);
        return blogRepository.findTop(pageable);
    }

    @Override
    public Page<Blog> searchBlogs(String query, Pageable pageable) {
        return blogRepository.findByQuery(query,pageable);
    }

    /**
     * 添加一个博客
     * @param blog
     * @return 返回添加的blog对象
     */
    @Override
    @Transactional
    public Blog saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);
        return blogRepository.save(blog);
    }

    /**
     * 更新（修改）博客
     * @param id
     * @param blog
     * @return 返回修改的blog对象
     */
    @Override
    @Transactional
    public Blog updateBlog(int id, Blog blog) {
        Blog b = blogRepository.getOne(id);
        if (b == null){
            throw new MyNotFoundException("该博客不存在！");
        }
        //更新是只用前端传来的非空字段覆盖 b
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }



    /**
     * 删除一个博客
     * @param id
     */
    @Override
    @Transactional
    public void deleteBlog(int id) {
        blogRepository.deleteById(id);
    }
}
